package com.bryant.demo05.ui.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bryant.demo05.R
import com.bryant.demo05.base.BaseBindingActivity
import com.bryant.demo05.databinding.AcWeatherDetailBinding
import com.bryant.demo05.storage.CityData
import com.bryant.demo05.storage.FavoriteManager
import com.bryant.demo05.ui.map.MapActivity
import com.bryant.demo05.ui.video.Media3PlayerActivity
import com.bryant.demo05.utils.WeatherUtils
import com.qweather.sdk.response.weather.WeatherDaily


class DetailActivity : BaseBindingActivity<AcWeatherDetailBinding>(), WeatherDetailView {
    // --------------------------------- 变量定义---------------------------------
    private var cityName = ""
    private var latitude = ""
    private var longitude = ""

    private var mPresenter: WeatherDetailPresenter? = null
    private var mWeather = ""
    private var mTemperature = ""
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


    // --------------------------------- OnCreate---------------------------------
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //  初始化 mPresenter
        /*
        * 作用是初始化 DetailActivity 中的 mPresenter 成员变量。
它创建了一个 WeatherDetailPresenter 实例，并传入当前 Activity (this) 和一个 WeatherDetailInteractor 实例作为参数。
这个 Presenter 负责协调 View（即 DetailActivity）与 Model（即 WeatherDetailInteractor）之间的交互，符合 MVP 架构模式。

        *
        * */
        /*
        ❗不可以将第29行代码放到后面两个方法之后执行，因为这会导致后续对 mPresenter 的访问都为 null，影响功能正常运行。
         ✅ 正确顺序应保持为：先初始化 mPresenter，再调用依赖它的其他方法
        * */
        mPresenter = WeatherDetailPresenter(this, WeatherDetailInteractor())
        // 1. 接收跳转传进来的参数
        getParamsFromIntent()
        // 2. 获取数据
        getData()

        // 3. 设置点击事件
        setOnclickEvent()

        // 4. 查询当前城市是否被收藏
        refreshStarStatus(FavoriteManager.isFavorite(cityName))

    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


    // --------------------------------- initBinding - 绑定View------------------------------------
    override fun initBinding(layoutInflater: LayoutInflater): AcWeatherDetailBinding {
        return AcWeatherDetailBinding.inflate(layoutInflater)
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


    // --------------------------------- 获取Activity跳转参数 ---------------------------------------
    private fun getParamsFromIntent() {
        cityName = intent.getStringExtra("cityName") ?: ""
        latitude = intent.getStringExtra("latitude") ?: ""
        longitude = intent.getStringExtra("longitude") ?: ""
        // 获取到参数之后设置给Presenter
        mPresenter?.setCityName(cityName)
        mPresenter?.setLocation(latitude, longitude)
        binding.detailTodayCard.tvCityName.text = cityName
    }

    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



    // --------------------------------- 获取3天天气数据成功 ---------------------------------
    @SuppressLint("SetTextI18n")
    override fun refreshTodayDataSuccess(weather: WeatherDaily) {
        hideLoading()
        binding.detailTodayCard.llCurrentWeatherContainer.visibility = View.VISIBLE

        var todayTemp = weather.tempMin + "° / " + weather.tempMax + "°"
        binding.detailTodayCard.tvTemperature.text = todayTemp

        // mPresenter?.setWeatherAndTemperature(weather.textDay, todayTemp)

        //白天、夜间天气
        refreshDayNightMoonPhase(weather)

        //湿度、紫外线强度指数、气压
        binding.detailTodayCard.humidityUvPressure.tvName1.text = "湿度"
        binding.detailTodayCard.humidityUvPressure.tvValue1.text = weather.humidity
        binding.detailTodayCard.humidityUvPressure.tvName2.text = "紫外线强度指数"
        binding.detailTodayCard.humidityUvPressure.tvValue2.text = weather.uvIndex
        binding.detailTodayCard.humidityUvPressure.tvName3.text = "气压"
        binding.detailTodayCard.humidityUvPressure.tvValue3.text = weather.pressure + "hPa"

        //日降水量，能见度
        binding.detailTodayCard.rainVisContainer.tvName1.text = "日降水量"
        binding.detailTodayCard.rainVisContainer.tvValue1.text = weather.precip + " mm"
        binding.detailTodayCard.rainVisContainer.tvName2.text = "能见度"
        binding.detailTodayCard.rainVisContainer.tvValue2.text = weather.vis + "km"
        binding.detailTodayCard.rainVisContainer.tvName3.text = ""
        binding.detailTodayCard.rainVisContainer.tvValue3.text = ""
        //日出日落
        binding.detailTodayCard.tvSunriseSunset.text =
            "日出时间：" + weather.sunrise + " 日落时间：" + weather.sunset
        //月出月落
        binding.detailTodayCard.tvMoonriseMoonset.text =
            "月出时间：" + weather.moonrise + " 月落时间：" + weather.moonset
        //风况
        binding.detailTodayCard.tvDayWindNightWind.text =
            "白天风况：" + weather.windDirDay + weather.windScaleDay + "级 风速：" + weather.windSpeedDay + "km/h\n夜间风况：" + weather.windDirNight + weather.windScaleNight + "级 风速：" + weather.windSpeedNight + "km/h"
    }

    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


    // --------------------------------- 获取3天天气数据失败 ---------------------------------
    override fun refreshTodayDataFailed(error: String) {
        hideLoading()
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$


    // --------------------------------- 获取数据---------------------------------
    private fun getData() {
        showLoading()
        mPresenter?.get3DayWeather()
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



    // --------------------------------- 刷新白天、夜间天气, 月相 ---------------------------------
    fun refreshDayNightMoonPhase(weather: WeatherDaily) {
        binding.detailTodayCard.weatherMoonPhase.tvName1.text = "白天天气"
        binding.detailTodayCard.weatherMoonPhase.tvValue1.text = weather.textDay
        var textDayIconCode = "_" + weather.iconDay.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textDayIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, textDayIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon1.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon1.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon1.visibility = View.GONE
        }

        binding.detailTodayCard.weatherMoonPhase.tvName2.text = "夜间天气"
        binding.detailTodayCard.weatherMoonPhase.tvValue2.text = weather.textNight
        var textNightIconCode = "_" + weather.iconNight.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, textNightIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, textNightIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon2.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon2.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon2.visibility = View.GONE
        }

        binding.detailTodayCard.weatherMoonPhase.tvName3.text = "月相"
        binding.detailTodayCard.weatherMoonPhase.tvValue3.text = weather.moonPhase

        var moonPhaseIconCode = "_" + weather.moonPhaseIcon.replace("-", "_")
        if (WeatherUtils.isDrawableInRClass(this, moonPhaseIconCode)) {
            val drawable = WeatherUtils.getDrawableByName(this, moonPhaseIconCode)
            drawable?.let {
                binding.detailTodayCard.weatherMoonPhase.ivIcon3.setImageDrawable(drawable)
            }
            binding.detailTodayCard.weatherMoonPhase.ivIcon3.visibility = View.VISIBLE
        } else {
            binding.detailTodayCard.weatherMoonPhase.ivIcon3.visibility = View.GONE
        }
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    // --------------------------------- 点击事件 ---------------------------------
    private fun setOnclickEvent() {
        // 1. 视频播放点击
        binding.detailTodayCard.ivVideoIcon.setOnClickListener {
            var intent = Intent(this, Media3PlayerActivity::class.java)
            startActivity(intent)
        }
        // 2.  收藏 点击事件
        binding.detailTodayCard.ivDetailStarCity.setOnClickListener {
            // 切换收藏状态并获取新状态
            val isNowFavorite = FavoriteManager.toggleFavorite(
                CityData(cityName, longitude.toDouble(), latitude.toDouble(), mWeather, mTemperature)
            )
            refreshStarStatus(isNowFavorite)
            // 显示提示
            Toast.makeText(this, if (isNowFavorite) "收藏成功" else "取消收藏", Toast.LENGTH_SHORT).show()
        }

        // 3. 地图 点击
        binding.detailTodayCard.ivLocationIcon.setOnClickListener {
            val intent = Intent(this, MapActivity::class.java)
            // 携带参数
            intent.putExtra("latitude", latitude)
            intent.putExtra("longitude", longitude)
            startActivity(intent)
        }
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    // --------------------------------- 设置天气和温度 -------------------------------
    fun setWeatherAndTemperature(weather: String, temperature: String) {
        mWeather = weather
        mTemperature = temperature
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    // --------------------------------------- 刷新收藏状态 -----------------------------------------
    fun refreshStarStatus(isStar: Boolean) {
        if (isStar) {
            binding.detailTodayCard.ivDetailStarCity.setImageResource(R.mipmap.icon_stared)
        } else {
            binding.detailTodayCard.ivDetailStarCity.setImageResource(R.mipmap.icon_detail_star)
        }
    }
    // $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$



}